package com.sz.mes.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.file.util.ExcelHelper;
import com.diboot.iam.dto.IamUserSearchDTO;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.vo.IamUserVO;
import com.sz.mes.entity.Material;
import com.sz.mes.entity.warehouse.LatticeGoods;
import com.sz.mes.excel.model.GoodsExportModel;
import com.sz.mes.excel.model.IamUserExportModel;
import com.sz.mes.mapper.GoodsMapper;
import com.sz.mes.mapper.MaterialMapper;
import com.sz.mes.mapper.warehouse.LatticeGoodsMapper;
import com.sz.mes.vo.MaterialListVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.Goods;
import com.sz.mes.dto.GoodsDTO;
import com.sz.mes.vo.GoodsListVO;
import com.sz.mes.vo.GoodsDetailVO;
import com.sz.mes.service.GoodsService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 商品 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-06-14
 * Copyright © szhs
 */
@RestController
@RequestMapping("/goods")
@BindPermission(name = "商品")
@Slf4j
public class GoodsController extends BaseCustomCrudRestController<Goods> {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private LatticeGoodsMapper latticeGoodsMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    // @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(GoodsDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getGoodsName())) {
            goodsQueryWrapper.like("goods_name", queryDto.getGoodsName());
        } else if (!StringUtils.isEmpty(queryDto.getGoodsCode())) {
            goodsQueryWrapper.like("goods_code", queryDto.getGoodsCode());
        } else {
//            return super.getViewObjectList(queryDto, pagination.setOrderBy("goods_code:ASC"), GoodsListVO.class);
            return super.getViewObjectList(queryDto, pagination.setOrderBy("id:ASC"), GoodsListVO.class);
        }
        return super.getEntityListWithPaging(goodsQueryWrapper, pagination.setOrderBy("id:ASC"));
    }

    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, GoodsDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody Goods entity) throws Exception {
        QueryWrapper<Goods> qw = new QueryWrapper<>();
        qw.eq("goods_code", entity.getGoodsCode());
        qw.eq("is_deleted", 0);
        Goods goods = goodsMapper.selectOne(qw);
        if (goods == null) {
            return super.createEntity(entity);
        } else {
            return JsonResult.FAIL_OPERATION("物料已存在");
        }
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    // @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody Goods entity) throws Exception {
        QueryWrapper<Goods> qw = new QueryWrapper<>();
        qw.eq("goods_code", entity.getGoodsCode());
        qw.eq("is_deleted", 0);
        Goods goods = goodsMapper.selectOne(qw);
        Goods currentGoods = goodsMapper.selectById(id);
        if (entity.getGoodsCode().equals(currentGoods.getGoodsCode())) {
            return super.updateEntity(id, entity);
        } else {
            if (goods != null) {
                return JsonResult.FAIL_EXCEPTION("物料已存在");
            } else {
                return super.updateEntity(id, entity);
            }
        }
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    // @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        QueryWrapper<LatticeGoods> latticeGoodsQueryWrapper = new QueryWrapper<>();
        latticeGoodsQueryWrapper.eq("goods_id", id);
        LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(latticeGoodsQueryWrapper);
        if (latticeGoods != null) {
            return JsonResult.FAIL_EXCEPTION("该物料在仓库中仍有库存，请清完库存后再删除");
        } else {
            return goodsService.deleteById(id);
        }
    }

    /**
     * 根据idList批量删除资源对象
     *
     * @param idList
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    // @BindPermission(name = OperationCons.LABEL_BATCH_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batchDelete")
    public JsonResult batchDelete(@RequestBody List<Long> idList) throws Exception {
        return super.batchDeleteEntities(idList);
    }

    /**
     * excel导入
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/excel")
    public JsonResult insert(@Valid @RequestBody Goods entity) throws Exception {
        /* List<String> GoodsCodeList = new ArrayList<>();
        String excelData = entity.getExcelData();
        JSONArray objects = JSONObject.parseArray(excelData);
        for (Object object : objects) {
            HashMap<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            String goodsCode = map.get("料号");
            GoodsCodeList.add(goodsCode);
        }
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        for (String goodsCode : GoodsCodeList) {
            queryWrapper.eq("goods_code", goodsCode);
            try {
                //判断数据库是否已经存在
                Goods goods = goodsMapper.selectOne(queryWrapper);
                if (goods == null) {
                    return goodsService.insert(entity);
                } else {
                    return JsonResult.FAIL_OPERATION("物料已存在,导入失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.FAIL_OPERATION("物料已存在,导入失败");
            }
        }
        return JsonResult.OK();*/
        try {
            return goodsService.insert(entity);
        } catch (Exception e) {
            throw e;
            // return JsonResult.FAIL_OPERATION("物料已存在,导入失败");
        }
    }

    /**
     * 根据物料编号查询物料id
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.LABEL_DETAIL)
    @GetMapping("/getGoodsId/{goodsCode}")
    public JsonResult selectGoodsId(@PathVariable("goodsCode") String goodsCode) throws Exception {
        return goodsService.selectGoodsId(goodsCode);
    }

    /**
     * 物料列表导出
     * @param goodsDTO
     * @return
     * @throws Exception
     */
    @Log(operation = "导出物料列表", businessObj = "Goods")
    // @BindPermission(name = OperationCons.LABEL_EXPORT, code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(GoodsDTO goodsDTO, @RequestParam(value = "columns", required = false) List<String> columns, HttpServletResponse response) throws Exception {
        QueryWrapper<GoodsDTO> queryWrapper = super.buildQueryWrapperByQueryParams(goodsDTO);
        List<Goods> goodsList = goodsService.getViewObjectList(queryWrapper, null, Goods.class);
        if (V.isEmpty(goodsList)) {
            return new JsonResult(Status.FAIL_OPERATION, "物料列表为空，导出失败");
        }
        String fileName = "物料列表导出_" + D.today() + ".xlsx";
        List<GoodsExportModel> dataList = this.entityList2ExcelList(goodsList);
        ExcelHelper.exportExcel(response, fileName, GoodsExportModel.class, columns, dataList);
        return null;
    }

    /**
     * 实体列表转excel列表
     * @param goodsList
     * @return
     */
    private List<GoodsExportModel> entityList2ExcelList(List<Goods> goodsList) {
        if (V.isEmpty(goodsList)) {
            return Collections.emptyList();
        }
        List<GoodsExportModel> excelModelList = new ArrayList<>();
        for (Goods goods : goodsList) {
            GoodsExportModel exportModel = new GoodsExportModel();
            BeanUtils.copyProperties(goods, exportModel);
            excelModelList.add(exportModel);
        }
        return excelModelList;
    }
}
